<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 报表
 *
 * @icon fa fa-circle-o
 */
class Report extends Backend {

    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
    }

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');

            $filter = (array) json_decode($filter, TRUE);

            $type = 1;

            if (isset($filter['type'])) {
                $type = $filter['type'];
            }

            $is_search = 0;
            $time = [];
            if (isset($filter['createtime'])) {
                $v = str_replace(' - ', ',', $filter['createtime']);
                $time = array_slice(explode(',', $v), 0, 2);
                $is_search = 1;
            } else {
                if ($type == 1) {
                    $time[0] = date('Y-m-d 00:00:00', strtotime('-6 days', time()));
                }

                if ($type == 2) {
                    $time[0] = date('Y-m-01 00:00:00');
                }

                if ($type == 3) {
                    $time[0] = date('Y-01-01 00:00:00');
                }

                if ($type == 4) {
                    $time[0] = '2018-01-01 00:00:00';
                }
                $time[1] = date('Y-m-d 23:59:59', time());
            }

            $day_list = [];

            //日报表
            if ($type == 1) {
                $diff = timeDiff(strtotime($time[0]), strtotime($time[1]));
                $diff_day = $diff['day'];

                for ($i = 0; $i <= $diff_day; $i++) {
                    $day_time = strtotime('+' . $i . ' days', strtotime($time[0]));
                    $day_list[] = ['day' => date('Y-m-d', $day_time), 'start' => date('Y-m-d 00:00:00', $day_time), 'end' => date('Y-m-d 23:59:59', $day_time)];
                }
                $total = $diff_day;
            }

            //周报表
            if ($type == 2) {

                $diff = diffDate(date('Y-m-d', strtotime($time[0])), date('Y-m-d', strtotime($time[1])));

                $diff_month = $diff['month'];

                for ($m = $diff_month; $m >= 0; $m--) {
                    $firstday = strtotime("-" . $m . " months" . date('Y-m-01', strtotime($time[1])));

                    $week_num = 5;
                    if ($is_search) {

                        $date_now = date('j'); //得到今天是几号
                        $cal_result = ceil($date_now / 7); //计算是第几个星期几
                        $week_num = $cal_result + 1;
                        $firstday = strtotime("-" . $m . " months" . date('Y-m-d', strtotime($time[1])));
                    }


                    //计算本月头一天的星期一
                    $monday = $firstday - 86400 * (date('N', $firstday) - 1); //计算第一个周一的日期
                    //由于每个月只有四周 让 $i 从 1 到 5 增加即可
                    for ($i = 0; $i <= $week_num; $i++) {
                        $start = date("Y-m-d", $monday + ($i - 1) * 86400 * 7); //起始周一
                        $end = date("Y-m-d", $monday + $i * 86399 * 7); //结束周日
                        if (date('Y-m', strtotime($end)) != date('Y-m', $firstday)) {
                            continue;
                        }

                        if (date('Y-m-d', strtotime($start)) > date('Y-m-d', strtotime($time[1]))) {
                            continue;
                        }


                        $day_list[] = ['day' => $start . '-' . $end, 'start' => $start . ' 00:00:00', 'end' => $end . ' 23:59:59'];
                    }
                }
                $total = count($day_list);
            }

            array_reverse($day_list);

            //月报表
            if ($type == 3) {
                $diff = diffDate(date('Y-m-d', strtotime($time[0])), date('Y-m-d', strtotime($time[1])));

                $diff_month = $diff['month'];

                for ($i = $diff_month; $i >= 0; $i--) {
                    $month = strtotime("-" . $i . " months" . date('Y-m-d', strtotime($time[1])));

                    $day_list[] = ['day' => date('Y-m', $month), 'start' => date('Y-m-01 00:00:00', $month), 'end' => date('Y-m-01 00:00:00', strtotime("+1 months" . date('Y-m-d', $month)))];
                }

                $total = count($diff_month + 1);
            }

            //年报表
            if ($type == 4) {
                $diff = diffDate('2018-01-01', date('Y-m-d', strtotime($time[0])));

                $diff_year = $diff['year'];

                for ($i = $diff_year; $i >= 0; $i--) {
                    $year = strtotime("-" . $i . " year" . date('Y-m-d', strtotime($time[0])));

                    $day_list[] = ['day' => date('Y', $year), 'start' => date('Y-01-01 00:00:00', $year), 'end' => date('Y-12-31 23:59:59', $year)];
                }

                $total = count($diff_year + 1);
            }

            $list = [];
            foreach ($day_list as $val) {
                $data['day'] = $val['day'];
                $data['user'] = db('users')->whereTime('createtime', 'between', [$val['start'], $val['end']])->count();
                $data['box'] = db('user_box')->whereTime('place_time_start', 'between', [$val['start'], $val['end']])->count();
                $data['order'] = db('order')->whereTime('createtime', 'between', [$val['start'], $val['end']])->where('status', 10)->where('type', 1)->count();
                $data['order_total'] = db('order')->whereTime('createtime', 'between', [$val['start'], $val['end']])->where('status', 10)->where('type', 1)->sum('pay_price');
                $data['pv'] = db('page_view')->whereTime('createtime', 'between', [$val['start'], $val['end']])->count();
                $data['uv'] = db('user_view')->whereTime('createtime', 'between', [$val['start'], $val['end']])->count();
                $data['damage'] = db('damage')->whereTime('createtime', 'between', [$val['start'], $val['end']])->sum('damage_amount');
                $data['start'] = $val['start'];
                $data['end'] = $val['end'];
                $list[] = $data;
            }


            $result = array("total" => $total, "rows" => array_reverse($list));

            return json($result);
        }
        return $this->view->fetch();
    }

    public function user() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = db('users')->whereTime('createtime', 'between', [$start, $end])->count();


            $list = db('users')
                    ->where($where)
                    ->whereTime('createtime', 'between', [$start, $end])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            $this->assign('start', $start);
            $this->assign('end', $end);
        }
        return $this->view->fetch('show');
    }

    public function box() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = db('user_box')->whereTime('place_time_start', 'between', [$start, $end])->count();


            $list = db('user_box')
                    ->where($where)
                    ->whereTime('place_time_start', 'between', [$start, $end])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            $this->assign('start', $start);
            $this->assign('end', $end);
        }
        return $this->view->fetch('show');
    }

    public function order() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = db('order')->whereTime('createtime', 'between', [$start, $end])->where('status', 10)->where('type', 1)->count();

            $model = new \app\admin\model\Order;

            $list = $model
                    ->alias('o')
                    ->field('o.*,ub.box_no,fa_users.nick_name,fa_users.phone,ub.province_name,ub.city_name,ub.area_name,ub.quarters_id,ub.room_id,ub.unit_id')
                    ->join('fa_users', 'fa_users.user_id = o.user_id', 'left')
                    ->join('fa_user_box ub', 'ub.user_id = o.user_id and ub.status=1', 'left')
                    ->where($where)
                    ->whereTime('o.createtime', 'between', [$start, $end])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            $this->assign('start', $start);
            $this->assign('end', $end);
        }
        return $this->view->fetch('show');
    }

    public function pv() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = db('page_view')->whereTime('createtime', 'between', [$start, $end])->count();


            $list = db('page_view')
                    ->alias('pv')
                    ->join('fa_users u', 'u.user_id = pv.user_id', 'left')
                    ->where($where)
                    ->whereTime('pv.createtime', 'between', [$start, $end])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            $this->assign('start', $start);
            $this->assign('end', $end);
        }
        return $this->view->fetch('show');
    }

    public function uv() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = db('user_view')->whereTime('createtime', 'between', [$start, $end])->count();


            $list = db('user_view')
                    ->alias('uv')
                    ->join('fa_users u', 'u.user_id = uv.user_id', 'left')
                    ->where($where)
                    ->whereTime('uv.createtime', 'between', [$start, $end])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            $this->assign('start', $start);
            $this->assign('end', $end);
        }
        return $this->view->fetch('show');
    }

    public function damage() {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = db('damage')->whereTime('createtime', 'between', [$start, $end])->count();

            $model = new \app\admin\model\Damage;

            $list = $model
                    ->field('fa_damage.*,fa_user_box.box_no,fa_user_box.user_box_id,fa_user_box.user_id,fa_user_box.province_name,fa_user_box.city_name,fa_user_box.area_name,fa_user_box.quarters_id,fa_user_box.unit_id,fa_user_box.room_id,fa_user_box.contacts,fa_user_box.telephone')
                    ->join('fa_user_box', 'fa_damage.user_box_id = fa_user_box.user_box_id', 'left')
                    ->whereTime('fa_damage.createtime', 'between', [$start, $end])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    $val['sum_amount'] = db('damage')->where(['user_box_id' => $val['user_box_id']])->sum('damage_amount');
                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                }
                unset($val);
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $start = $this->request->get("start", '');
            $end = $this->request->get("end", '');

            $this->assign('start', $start);
            $this->assign('end', $end);
        }

        return $this->view->fetch('show');
    }

    public function goods() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function recharge() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $otherwhere[] = ['type', '=', 10];
            $otherwhere[] = ['status', '=', 10];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, $otherwhere);
            $total = db('order')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = db('order')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

}
